import { getPool } from '../db'
import type { Task, AppSettings } from '@/types'

export const TaskService = {
  async create(task: Task) {
    const pool = await getPool()
    const [result] = await pool.execute(
      `INSERT INTO tasks (id, type, status, files, options, created_at, updated_at)
       VALUES (?, ?, ?, ?, ?, NOW(), NOW())`,
      [
        task.id,
        task.type,
        task.status,
        JSON.stringify(task.files),
        JSON.stringify(task.options)
      ]
    )
    return result
  },

  async update(id: string, updates: Partial<Task>) {
    const pool = await getPool()
    const sets: string[] = []
    const values: any[] = []

    Object.entries(updates).forEach(([key, value]) => {
      if (key === 'files' || key === 'options' || key === 'result') {
        sets.push(`${key} = ?`)
        values.push(JSON.stringify(value))
      } else {
        sets.push(`${key} = ?`)
        values.push(value)
      }
    })

    values.push(id)

    const [result] = await pool.execute(
      `UPDATE tasks SET ${sets.join(', ')}, updated_at = NOW() WHERE id = ?`,
      values
    )
    return result
  },

  async getAll(): Promise<Task[]> {
    const pool = await getPool()
    const [rows] = await pool.execute('SELECT * FROM tasks ORDER BY created_at DESC')
    return (rows as any[]).map(row => ({
      ...row,
      files: JSON.parse(row.files),
      options: JSON.parse(row.options),
      result: row.result ? JSON.parse(row.result) : undefined
    }))
  },

  async getById(id: string): Promise<Task | undefined> {
    const pool = await getPool()
    const [rows] = await pool.execute('SELECT * FROM tasks WHERE id = ?', [id])
    const row = (rows as any[])[0]
    if (!row) return undefined

    return {
      ...row,
      files: JSON.parse(row.files),
      options: JSON.parse(row.options),
      result: row.result ? JSON.parse(row.result) : undefined
    }
  }
}

export const SettingsService = {
  async get(key: string): Promise<string | null> {
    const pool = await getPool()
    const [rows] = await pool.execute('SELECT value FROM settings WHERE `key` = ?', [key])
    const row = (rows as any[])[0]
    return row ? row.value : null
  },

  async set(key: string, value: string) {
    const pool = await getPool()
    await pool.execute(
      'INSERT INTO settings (`key`, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = ?',
      [key, value, value]
    )
  },

  async getAll(): Promise<Record<string, string>> {
    const pool = await getPool()
    const [rows] = await pool.execute('SELECT * FROM settings')
    return (rows as any[]).reduce((acc, row) => {
      acc[row.key] = row.value
      return acc
    }, {} as Record<string, string>)
  }
} 